package financial

import (
	"encoding/json"
	"fmt"
	"ltbz/cultural_tourism_api/controllers"
	"ltbz/cultural_tourism_api/models"
	"ltbz/cultural_tourism_api/models/financial"
	"ltbz/cultural_tourism_api/utils"
	"os"
	"strconv"
	"time"

	"github.com/tealeg/xlsx"
)

// 故宫收入
type ImperialPalaceController struct {
	controllers.BaseAuthController
}

// @Title 获取故宫收入-财务数据
// @Description 获取故宫收入-财务数据
// @Success 200 {object} financial.ImperialPalaceFinancialData
// @router /imperial_palace/financial_data [post]
func (this *ImperialPalaceController) ImperialPalaceFinancialData() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	obj := new(financial.ImperialPalace)
	fmt.Println(obj)

	resp := new(financial.ImperialPalaceFinancialData)

	// 当日数据
	{
		//date := time.Now().Format(utils.FormatDate)
		//var condition string
		//var pars []interface{}
		//condition += ` AND create_date=? `
		//pars = append(pars, date)
		//list, err := obj.GetTradeAmountStatistics(condition, pars)
		//if err != nil {
		//	br.Msg = "获取失败"
		//	br.ErrMsg = "获取失败"
		//	return
		//}
		//dayFinancialDataItem := new(financial.FinancialDataItem)
		//for _, v := range list {
		//	if v.TradeStatus == "待使用" {
		//		dayFinancialDataItem.VipIncome += v.TradeMoney
		//	} else if v.TradeStatus == "已使用" || v.TradeStatus == "已生效" {
		//		dayFinancialDataItem.SvipIncome += v.TradeMoney
		//	}
		//}
		//resp.CurrentDay = dayFinancialDataItem

		date := time.Now().Format(utils.FormatDate)
		var condition string
		var pars []interface{}
		condition += ` AND create_date=? `
		pars = append(pars, date)
		condition += ` AND trade_status IN('待使用','已使用','已生效') `
		currentDay, err := obj.GetTradeOrderStatistics(condition, pars)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取失败,Err:" + err.Error()
			return
		}
		dayFinancialDataItem := new(financial.FinancialDataItem)
		dayFinancialDataItem.TradeOrderTotal = currentDay.TradeOrderTotal
		dayFinancialDataItem.TradeOrderTotalMoney = currentDay.TradeOrderTotalMoney
		resp.CurrentDay = dayFinancialDataItem
	}
	// 当周数据
	{
		var condition string
		var pars []interface{}

		//获取周开始和结束日期
		weekStart := utils.GetNowWeekMonday()
		weekEnd := utils.GetNowWeekLastDay()

		condition += ` AND create_date>=? `
		pars = append(pars, weekStart)

		condition += ` AND create_date<=? `
		pars = append(pars, weekEnd)

		//list, err := obj.GetTradeAmountStatistics(condition, pars)
		//if err != nil {
		//	br.Msg = "获取"
		//}
		//weekFinancialDataItem := new(financial.FinancialDataItem)
		//for _, v := range list {
		//	if v.TradeStatus == "待使用" {
		//		weekFinancialDataItem.VipIncome += v.TradeMoney
		//	} else if v.TradeStatus == "已使用" || v.TradeStatus == "已生效" {
		//		weekFinancialDataItem.SvipIncome += v.TradeMoney
		//	}
		//}

		condition += ` AND trade_status IN('待使用','已使用','已生效') `
		currentWeek, err := obj.GetTradeOrderStatistics(condition, pars)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取失败,Err:" + err.Error()
			return
		}

		weekFinancialDataItem := new(financial.FinancialDataItem)

		weekFinancialDataItem.TradeOrderTotalMoney = currentWeek.TradeOrderTotalMoney
		weekFinancialDataItem.TradeOrderTotal = currentWeek.TradeOrderTotal
		resp.CurrentWeek = weekFinancialDataItem
	}
	// 当月数据
	{
		var condition string
		var pars []interface{}

		now := time.Now()
		//获取月开始和结束日期
		monthStart, monthEnd := utils.GetMonthStartAndEnd(strconv.Itoa(now.Year()), strconv.Itoa(int(now.Month())))

		condition += ` AND create_date>=? `
		pars = append(pars, monthStart)

		condition += ` AND create_date<=? `
		pars = append(pars, monthEnd)

		//list, err := obj.GetTradeAmountStatistics(condition, pars)
		//if err != nil {
		//	br.Msg = "获取"
		//}
		//monthFinancialDataItem := new(financial.FinancialDataItem)
		//for _, v := range list {
		//	if v.TradeStatus == "待使用" {
		//		monthFinancialDataItem.VipIncome += v.TradeMoney
		//	} else if v.TradeStatus == "已使用" || v.TradeStatus == "已生效" {
		//		monthFinancialDataItem.SvipIncome += v.TradeMoney
		//	}
		//}
		//resp.CurrentMonth = monthFinancialDataItem

		condition += ` AND trade_status IN('待使用','已使用','已生效') `
		currentMonth, err := obj.GetTradeOrderStatistics(condition, pars)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取失败,Err:" + err.Error()
			return
		}
		monthFinancialDataItem := new(financial.FinancialDataItem)
		monthFinancialDataItem.TradeOrderTotalMoney = currentMonth.TradeOrderTotalMoney
		monthFinancialDataItem.TradeOrderTotal = currentMonth.TradeOrderTotal
		resp.CurrentMonth = monthFinancialDataItem
	}

	// 总计数据
	{
		var condition string
		var pars []interface{}

		//list, err := obj.GetTradeAmountStatistics(condition, pars)
		//if err != nil {
		//	br.Msg = "获取"
		//}
		//totalFinancialDataItem := new(financial.FinancialDataItem)
		//for _, v := range list {
		//	if v.TradeStatus == "待使用" {
		//		totalFinancialDataItem.VipIncome += v.TradeMoney
		//	} else if v.TradeStatus == "已使用" || v.TradeStatus == "已生效" {
		//		totalFinancialDataItem.SvipIncome += v.TradeMoney
		//	}
		//}
		//resp.Total = totalFinancialDataItem

		condition += ` AND trade_status IN('待使用','已使用','已生效') `
		totalItem, err := obj.GetTradeOrderStatistics(condition, pars)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取失败,Err:" + err.Error()
			return
		}
		totalFinancialDataItem := new(financial.FinancialDataItem)
		totalFinancialDataItem.TradeOrderTotal = totalItem.TradeOrderTotal
		totalFinancialDataItem.TradeOrderTotalMoney = totalItem.TradeOrderTotalMoney
		resp.Total = totalFinancialDataItem
	}
	br.Msg = "获取成功"
	br.Ret = 200
	br.Data = resp
	return
}

// @Title 获取故宫收入-订单列表
// @Description 获取故宫收入-订单列表
// @Param	request	body financial.ImperialPalaceOrderListReq true "type json string"
// @Success 200 {object} financial.ImperialPalaceOrderListPageResp
// @router /imperial_palace/order_list [post]
func (this *ImperialPalaceController) ImperialPalaceOrderList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	body := this.Ctx.Input.RequestBody
	req := new(financial.ImperialPalaceOrderListReq)
	if string(body) != "" {
		err := json.Unmarshal(body, &req)
		if err != nil {
			br.Msg = "参数解析异常！"
			br.ErrMsg = "参数解析失败，Err:" + err.Error()
			return
		}
	}

	if req.PageSize <= 0 {
		req.PageSize = utils.PageSize20
	}
	if req.CurrentIndex <= 0 {
		req.CurrentIndex = 1
	}

	startSize := utils.StartIndex(req.CurrentIndex, req.PageSize)

	obj := new(financial.ImperialPalace)

	var condition string
	var pars []interface{}

	if req.TradeCode != "" {
		condition += " AND a.trade_code = ?"
		pars = append(pars, req.TradeCode)
	}

	if req.Mobile != "" {
		mobile := `%` + req.Mobile + `%`
		condition += " AND b.mobile LIKE ?"
		pars = append(pars, mobile)
	}

	if req.TradeStatus != "" {
		condition += " AND a.trade_status = ?"
		pars = append(pars, req.TradeStatus)
	}

	if req.StartTime != "" {
		condition += " AND a.create_date >= ?"
		pars = append(pars, req.StartTime)
	}

	if req.EndTime != "" {
		condition += " AND a.create_date <= ?"
		pars = append(pars, req.EndTime)
	}

	if req.GoodsName != "" {
		goodsName := `%` + req.GoodsName + `%`
		condition += " AND c.goods_name LIKE ?"
		pars = append(pars, goodsName)
	}

	if req.GoodsCode != "" {
		condition += " AND c.goods_code = ?"
		pars = append(pars, req.GoodsCode)
	}

	total, err := obj.GetImperialPalaceOrderPageCount(condition, pars)
	if err != nil {
		br.Msg = "获取数据失败！"
		br.ErrMsg = "获取数据失败，Err:" + err.Error()
		return
	}

	list, err := obj.GetImperialPalaceOrderPage(condition, pars, startSize, req.PageSize)
	if err != nil {
		br.Msg = "获取数据失败！"
		br.ErrMsg = "获取数据失败，Err:" + err.Error()
		return
	}

	page := utils.GetPaging(req.CurrentIndex, req.PageSize, total)

	resp := new(financial.ImperialPalaceOrderListPageResp)
	resp.Paging = page
	resp.List = list

	br.Msg = "获取成功"
	br.Ret = 200
	br.Data = resp
	return
}

// @Title 故宫收入-订单导出
// @Description 故宫收入-订单导出
// @Param	request	body financial.ImperialPalaceOrderListExportReq true "type json string"
// @Success 200
// @router /imperial_palace/order_list/export [get]
func (this *ImperialPalaceController) ImperialPalaceOrderListExport() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	body := this.Ctx.Input.RequestBody
	req := new(financial.ImperialPalaceOrderListExportReq)
	if string(body) != "" {
		err := json.Unmarshal(body, &req)
		if err != nil {
			br.Msg = "参数解析异常！"
			br.ErrMsg = "参数解析失败，Err:" + err.Error()
			return
		}
	}

	var condition string
	var pars []interface{}

	if req.TradeCode != "" {
		condition += "AND a.trade_code = ?"
		pars = append(pars, req.TradeCode)
	}

	if req.Mobile != "" {
		mobile := `%` + req.Mobile + `%`
		condition += "AND a.mobile LIKE ?"
		pars = append(pars, mobile)
	}

	obj := new(financial.ImperialPalace)
	list, err := obj.GetImperialPalaceOrderExportPage(condition, pars)
	if err != nil {
		br.Msg = "获取数据失败！"
		br.ErrMsg = "获取数据失败，Err:" + err.Error()
		return
	}

	xlsxFile := xlsx.NewFile()
	if err != nil {
		br.Msg = "生成文件失败"
		br.ErrMsg = "生成文件失败"
		return
	}
	style := xlsx.NewStyle()
	alignment := xlsx.Alignment{
		Horizontal: "center",
		Vertical:   "center",
		WrapText:   true,
	}

	style.Alignment = alignment
	style.ApplyAlignment = true
	if len(list) <= 0 {
		xlsxFile.AddSheet("暂无数据")
	}

	sheel, err := xlsxFile.AddSheet("智能桶用户")
	if err != nil {
		br.Msg = "新增Sheet失败"
		br.ErrMsg = "新增Sheet失败,Err:" + err.Error()
		return
	}

	titleRow := sheel.AddRow()
	titleRow.AddCell().SetValue("序号")
	titleRow.AddCell().SetValue("订单编号")
	titleRow.AddCell().SetValue("用户ID")
	titleRow.AddCell().SetValue("手机号")
	titleRow.AddCell().SetValue("商品编码")
	titleRow.AddCell().SetValue("商品名称")
	titleRow.AddCell().SetValue("数量")
	titleRow.AddCell().SetValue("单价(元)")
	titleRow.AddCell().SetValue("总计金额(元)")
	titleRow.AddCell().SetValue("付款金额")
	titleRow.AddCell().SetValue("付款时间")
	titleRow.AddCell().SetValue("订单状态")
	for _, v := range list {
		dataRow := sheel.AddRow()
		dataRow.AddCell().SetValue(v.TradeId)
		dataRow.AddCell().SetValue(v.TradeCode)
		dataRow.AddCell().SetValue(v.WxUserId)
		dataRow.AddCell().SetValue(v.Mobile)
		dataRow.AddCell().SetValue(v.GoodsCode)
		dataRow.AddCell().SetValue(v.GoodsName)
		dataRow.AddCell().SetValue(v.BuyGoodNum)
		dataRow.AddCell().SetValue(v.GoodsPrice)
		dataRow.AddCell().SetValue(v.TradeMoney)
		dataRow.AddCell().SetValue(v.TradeMoney)
		dataRow.AddCell().SetValue(v.PayTime)
		dataRow.AddCell().SetValue(v.TradeStatus)
	}
	pref := `故宫收入统计_`
	savePath := `./temp/` + pref + time.Now().Format(utils.FormatDateTimeUnSpace) + ".xlsx"
	err = xlsxFile.Save(savePath)
	if err != nil {
		br.Msg = "保存文件失败"
		br.ErrMsg = "保存文件失败,Err:" + err.Error()
		return
	}
	downloadFileName := pref + time.Now().Format(utils.FormatDateTimeUnSpace) + ".xlsx"
	this.Ctx.Output.Download(savePath, downloadFileName)
	defer func() {
		os.Remove(savePath)
	}()
	br.Msg = "导出成功！"
	br.Ret = 200
}
